package cn.azzhu.upload;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author azzhu
 * @create 2020-08-18 09:03:17
 */
@Controller
public class FileUploadController {

    @PostMapping("fileUpload")
    public String fileUpload(
            @RequestParam(name = "age",required = false,defaultValue = "10") int age,
            @RequestParam("file") MultipartFile[] multipartFiles,
            HttpServletRequest request) throws IOException {
        //获取普通表单项
        System.out.println(age);
        //处理文件上传项
        for (MultipartFile multipartFile : multipartFiles) {
            if(multipartFile.isEmpty()) {
                System.out.println("文件未上传");
            } else {
                // 得到上传的文件名
                String fileName = multipartFile.getOriginalFilename();
                // 得到服务器项目发布运行所在地址
                String path1 = request.getSession().getServletContext().getRealPath("upload") + File.separator;
                // 此处未使用UUID来生成唯一标识,用日期做为标识
                String path = path1 + new SimpleDateFormat("yyyyMMdd").format(new Date()) + fileName;
                // 查看文件上传路径,方便查找
                System.out.println(path);
                // 把文件上传至path的路径
                File localFile = new File(path);
                if (!localFile.exists()) {
                    localFile.mkdirs();
                }
                multipartFile.transferTo(localFile);
            }
        }
        return "hello";
    }

    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity()throws IOException
    {
        //从本地读取一个文件
        FileInputStream input = new FileInputStream(new File("D:\\44\\a.txt"));
        //构建一个缓存数组，数组大小给的就是文件的大小
        byte[] body = new byte[input.available()];
        input.read(body);
        input.close();

        //设置响应头，设置了以附件下载的形式
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=a.txt");
        HttpStatus statusCode = HttpStatus.OK;

        ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers, statusCode);
        return entity;
    }

}
